package com.guardchina.framework.util.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 描述：日期反序列化
 *
 * @author lwb
 * @date 2019/3/21 11:26
 */
public class LocalDateSerializer implements JsonDeserializer<LocalDate>, JsonSerializer<LocalDate> {

    private String datePattern;
    public LocalDateSerializer(String pattern){
        super();
        this.datePattern = pattern;
    }

    @Override
    public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String date = json.getAsJsonPrimitive().getAsString();
        return LocalDate.parse(date, DateTimeFormatter.ofPattern(datePattern));
    }

    @Override
    public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern(datePattern)));
    }
}
